package Mysql

import (
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"errors"
	"fmt"
	model "hello/models"
)

const secret = "www.Xiangmaster.com"

// 把每一步数据库操作封装成函数
// 待logic层根据业务需求调用
func InsertUser(User *model.User) (err error) {
	//对密码进行加密
	passwdnew := encryptPassword(User.Password)
	//执行数据库
	fmt.Println(User)
	sqlStr := `insert into user(user_id, username, password) values(?,?,?)`
	_, err = Db.Exec(sqlStr, User.UserId, User.UserName, passwdnew)
	if err != nil {
		fmt.Println(err)
		return err
	}

	return nil
}

func CheckUserExist(username string) (err error) {
	sqlStr := `select count(user_id) from user where username = ?`
	var count int
	err = Db.Get(&count, sqlStr, username)
	if err != nil {
		return err
	}

	if count > 0 {
		return errors.New("用户已经存在")
	}

	return nil
}

func encryptPassword(oPasswd string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPasswd)))
}

func Login(p *model.User) (err error) {
	passwd := p.Password
	fmt.Printf("login passwd:%v\n", passwd)
	fmt.Println(p)
	sqlStr := `select user_id,username,password from user where username=?`
	err = Db.Get(p, sqlStr, p.UserName)
	fmt.Println(p)
	if err == sql.ErrNoRows {
		return errors.New("用户不存在")
	}

	if err != nil {
		return err
	}

	password := encryptPassword(passwd)
	fmt.Printf("login passwd:%v\n", password)
	if password != p.Password {
		return errors.New("登录密码错误")
	}

	return nil
}
